package com.xiaoq.sites.endpoint;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xiaoq.RedisTemplate4JedisCluster;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.sites.entity.SitesPointEntity;
import com.xiaoq.sites.entity.SitesRouteEntity;
import com.xiaoq.sites.entity.SitesRoutePointEntity;
import com.xiaoq.sites.service.ISitesRouteApi;
import com.xiaoq.sites.service.ISitesService;
import com.xiaoq.sites.vo.RouteAdditionVo;
import com.xiaoq.sites.vo.RouteDetailVo;
import com.xiaoq.sites.vo.SitesPoint2Vo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1")
@Api(tags = "线路B端相关Api")
public class SitesRoute2BEndpoint {
	
	private static final Logger LOG = LoggerFactory.getLogger(SitesRoute2BEndpoint.class);
	
	private static final class Route2BListResponse extends GenericListResponse<RouteDetailVo> {};
	
	private static final class SitesPointListResponse extends GenericListResponse<SitesPoint2Vo>{}
	
	@Autowired
	private ISitesService msSitesApi;
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;
	
	@Autowired
	private ISitesRouteApi sitesRouteApi;
	
	@ApiOperation(value="景点关键字查询相关景点", notes="景点关键字查询相关景点")
	@ApiResponses({
		@ApiResponse(code = 200, response = SitesPointListResponse.class, message = "景点关键字查询相关景点")
	})
	@GetMapping(value="/sites/sitespoint", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> sitesPointVags(
			@RequestParam(value="pointName",required = true)@ApiParam(value="景点标题的关键词",required=true)String pointName,
			HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<SitesPointEntity> sitesPointList = msSitesApi.findByPointNameVag(pointName,shopId);
		List<SitesPoint2Vo> sitesPointVoList = new ArrayList<>();
		SitesPoint2Vo sitesPointVo = null;
		for(SitesPointEntity sitesPoint:sitesPointList){
			sitesPointVo = new SitesPoint2Vo();
			BeanUtils.copyProperties(sitesPoint, sitesPointVo);
			sitesPointVoList.add(sitesPointVo);
		}
		return SitesPointListResponse.listNoCount(sitesPointVoList);
		
	}
	
	@ApiOperation(value="查询线路列表", notes="根据景区ID查询线路列表")
	@ApiResponses({
		@ApiResponse(code = 200, response = Route2BListResponse.class, message = "查询线路列表")
	})
	@GetMapping(value="/sites/sites_route", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> routeList(HttpServletRequest request) {
		String errorMsg = "查询线路列表出错";
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		String sitesId = shopId;
		try {
			List<SitesRouteEntity> sitesRouteList = msSitesApi.findSitesRouteListBySitesId(sitesId);
			List<RouteDetailVo> list = new ArrayList<RouteDetailVo>();
			RouteDetailVo routeDetailVo = null;
			SitesPoint2Vo sitesPointVo = null;
			List<SitesPoint2Vo> sitesPointVoList = null;
			SitesPointEntity sitesPoint = null;
			for(SitesRouteEntity sitesRoute:sitesRouteList){
				String sitesRouteId = sitesRoute.getId();
				routeDetailVo = new RouteDetailVo();
				BeanUtils.copyProperties(sitesRoute, routeDetailVo);
				sitesPointVoList = new ArrayList<>();
				List<SitesRoutePointEntity> sitesRoutePointList = msSitesApi.findSitesRoutePointByRouteId(sitesRouteId);
				for(SitesRoutePointEntity sitesRoutePoint:sitesRoutePointList){
					sitesPointVo = new SitesPoint2Vo();
					String sitesPointId = sitesRoutePoint.getSitesPointId();
					int sitesPointSortNum = sitesRoutePoint.getSortNum();
					sitesPoint=msSitesApi.findSitesPointByPointId(sitesPointId);
					sitesPoint.setSortNum(sitesPointSortNum);
					BeanUtils.copyProperties(sitesPoint, sitesPointVo);
					sitesPointVoList.add(sitesPointVo);
				}
				routeDetailVo.setSitesPoints(sitesPointVoList);
				list.add(routeDetailVo);
				
			}
			return Route2BListResponse.listNoCount(list);
			
//			
//			List<String> sitesRouteIdList = null;
//			if(CollectionUtils.isNotEmpty(sitesRouteList)) {
//				
//				sitesRouteIdList = sitesRouteList.stream().map(sitesRoute -> sitesRoute.getId()).collect(Collectors.toList());
//				Map<String, List<SitesPointEntity>> routeId2SitesPointMap = msSitesApi.findSitesPointMapByRouteIdList(sitesRouteIdList);
//				
//				for (SitesRouteEntity sitesRoute : sitesRouteList) {
//					routeDetailVo = new RouteDetailVo();
//					BeanUtils.copyProperties(sitesRoute, routeDetailVo);
//					
//					List<SitesPointEntity> sitesPointEntitiesList = routeId2SitesPointMap.get(sitesRoute.getId());
//					if(CollectionUtils.isNotEmpty(sitesPointEntitiesList)) {
//						sitesPointVoList = new ArrayList<>();
//						for (SitesPointEntity sitesPointEntity : sitesPointEntitiesList) {
//							sitesPointVo = new SitesPointVo();
//							BeanUtils.copyProperties(sitesPointEntity, sitesPointVo);
//							sitesPointVoList.add(sitesPointVo);
//						}
//					}
//					Collections.sort(sitesPointVoList, new Comparator<SitesPointVo>() {
//						 public int compare(SitesPointVo spv1, SitesPointVo spv2) {
//				                //对线路上的景点进行升序排列
//				                if(spv1.getSortNum() > spv2.getSortNum()){
//				                    return 1;
//				                }
//				                if(spv1.getSortNum() == spv2.getSortNum()){
//				                    return 0;
//				                }
//				                return -1;
//				            }
//					});
//					routeDetailVo.setSitesPoints(sitesPointVoList);
//					
//					list.add(routeDetailVo);
//				}
//			}
//			
//			return Route2BListResponse.listNoCount(list);
		} catch (Exception e) {
			LOG.error(errorMsg,e);
			return GenericResponse.ng(errorMsg);
		}
	}
	/**
	 * 
	 * @param routeId
	 * @param sitesPointId
	 * @return
	 */
	@ApiOperation(value="在线路上移动景点位置(因为线路上可能添加有两个相同的景点这样通过线路Id和景点Id就不能获取了！)", notes="在线路上移动景点位置")
	@ApiResponses({
		@ApiResponse(code=200,response=GenericResponse.class,message="在线路上移动景点位置")
	})
	@PutMapping(value="/sites_route/{routeId}/sites_points", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> changeRouteSitesPoint(
									@PathVariable(value="routeId",required=true)@ApiParam(value="routeId",required=true)String routeId,
									@RequestParam(value="sortNum",required=true)@ApiParam(value="移动的景点的所在序号",required=true)Integer sortNum,
									@RequestParam(value="status",required=true)@ApiParam(value="上移为1下移为0",required=true)Integer status){
		
		boolean result = sitesRouteApi.changeRoutePoint(routeId, sortNum, status);
		if(result){
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("线路上移动一个景点失败");
		}
		
	}
	/**
	 * 在线路上添加一个新的景点
	 * @param routeId
	 * @param sitesPointId
	 * @return
	 */
	@ApiOperation(value="在线路上添加一个景点", notes="在线路上添加一个景点,要知道插在谁的后面")
	@ApiResponses({
		@ApiResponse(code=200,response=GenericResponse.class,message="在线路上添加一个景点")
	})
	@PostMapping(value="/sites_route/{routeId}/sites_points", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addRouteSitesPoint(
									@PathVariable(value="routeId",required=true)@ApiParam(value="routeId",required=true)String routeId,
									@RequestParam(value="pointName",required=true)@ApiParam(value="要插入景点的景点名称",required=true)String pointName,
									@RequestParam(value="sortNum",required=true)@ApiParam(value="sortNum(插入景点的前一个景点的序号如果是第一个景点传0)",required=true)Integer sortNum,
									@RequestParam(value="memo",required=false)@ApiParam(value="memo",required=false)String memo){
		LOG.info("线路上添加一个景点routeId"+routeId+"pointName："+pointName+"sortNum"+sortNum);
		SitesRouteEntity sitesRoute = sitesRouteApi.findById(routeId);
		String sitesId = null;
		if(sitesRoute!=null){
			sitesId = sitesRoute.getSitesId();
		}else{
			return GenericResponse.ng("没有指定的景区！");
		}
		SitesPointEntity sitesPoint = msSitesApi.findByPointName(pointName);
		LOG.info("查询得到的景点为:"+sitesPoint);
		if(sitesPoint==null){
			sitesPoint = new SitesPointEntity();
			sitesPoint.setName(pointName);
			sitesPoint.setRecIndex(0);
			sitesPoint.setSitesId(sitesId);
			boolean result = msSitesApi.addSitesPoint(sitesPoint);
			if(!result){
				return GenericResponse.ng("景点名称重复");
			}
//			sitesPoint = msSitesApi.findByPointName(pointName);
			LOG.info("新插入的景点为"+sitesPoint);
		}
		String sitesPointId = sitesPoint.getId();
		SitesRoutePointEntity sitesRoutePoint = new SitesRoutePointEntity();
		sitesRoutePoint.setRouteId(routeId);
		sitesRoutePoint.setSitesPointId(sitesPointId);
		sitesRoutePoint.setSortNum(sortNum);
		sitesRoutePoint.setMemo(memo);
		boolean queryResult = sitesRouteApi.findRoutePointByrouteIdAndPointId(routeId, sitesPointId);
		if(queryResult){
			return GenericResponse.ng("一条线路不能存在相同的景点！");
		}
		boolean result =  sitesRouteApi.addRoutePoint(sitesRoutePoint);
		if(result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("添加失败");
	}
	
	/**
	 * 为景区添加一条新的线路
	 * @param routeName
	 * @param routeAdditionVo
	 * @return
	 */
	@ApiOperation(value="添加线路" ,notes="添加旅游线路")
	@ApiResponses({
		@ApiResponse(code=200, response=GenericResponse.class, message="添加路线")
	})
	@PostMapping(value="/sites_route", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addRoute(@RequestBody RouteAdditionVo routeAdditionVo,HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		routeAdditionVo.setSitesId(shopId);
		SitesRouteEntity siteRouteEntity = new SitesRouteEntity();
		BeanUtils.copyProperties(routeAdditionVo,siteRouteEntity);
	    boolean routeAddResult = sitesRouteApi.addSitesRoute(siteRouteEntity);
	    if(routeAddResult){
	    	return GenericResponse.ok();
	    }
		
	    return GenericResponse.ng("线路名称不可重复！");
	}
	
	/**
	 * 根据线路id删除一条线路
	 * @param routeId
	 * @return
	 */
	@ApiOperation(value="删除线路",notes="删除旅游线路")
	@ApiResponses({
		@ApiResponse(code=200, response=GenericResponse.class,message="删除路线")
	})
	@DeleteMapping(value="/sites_route/{id}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?>  deleteRoute(@PathVariable(value="id",required=true)@ApiParam(value="线路Id",required=true)String id){ 
		boolean result = sitesRouteApi.delSitesRoute(id);
		if( result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("删除失败");
	}
	
	@ApiOperation(value="从线路上删除一个景点", notes="线路上删除一个景点后，后面的景点要前移")
	@ApiResponses({
		@ApiResponse(code=200,response=GenericResponse.class,message="线路上删除一个景点")
	})
	@DeleteMapping(value="/sites_route/{routeId}/sites_points/{sitesPointId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> delRouteSitesPoint(@PathVariable(value="routeId",required=true)@ApiParam(value="routeId",required=true)String routeId,@PathVariable(value="sitesPointId",required=true)@ApiParam(value="sitesPointId",required=true)String sitesPointId){

		boolean result = sitesRouteApi.delRoutePoint(routeId, sitesPointId);
		if(result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("删除失败");
	}

	
	@ApiOperation(value="修改线路" ,notes="修改旅游线路")
	@ApiResponses({
		@ApiResponse(code=200, response=GenericResponse.class, message="添加路线")
	})
	@PutMapping(value="/sites_route", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateRoute(@ModelAttribute(value="routeAdditionVo")@ApiParam(value="routeAdditionVo",required=true)RouteAdditionVo routeAdditionVo,HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		routeAdditionVo.setSitesId(shopId);
		SitesRouteEntity siteRouteEntity = new SitesRouteEntity();
		BeanUtils.copyProperties(routeAdditionVo,siteRouteEntity);
		boolean result = sitesRouteApi.updateRoute(siteRouteEntity);
		if(result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("修改失败");
	}

}
